/*
 * @Author       : xiangmin
 * @File         : element-table hooks封装
 * @Date         : 2023-06-16 12:48:35
 * @LastEditors  : xiangmin
 * @LastEditTime : 2023-11-24 10:32:58
 */

import type { Config } from '@/autoImport/request'
import { useHomeStore } from '@/store'
import type { ElPagination } from 'element-plus'

export type PaginationProps = InstanceType<typeof ElPagination>['$props']

interface UseTableConfig {
	url: string
	config?: Config
	immediate?: boolean
	params?: Record<string, any>
	currentPage?: number
	pageSize?: number
	pageSizeOptions?: number[]
	paginationOptions?: PaginationProps
	onSuccess?: Function
	onError?: Function
	onFilter?: Function
}

export default function <T, R extends TableData<T> = TableData<T>>({
	url,
	config,
	immediate = true,
	params = {},
	currentPage = 1,
	pageSize = useHomeStore().size,
	pageSizeOptions = [10, 15, 20, 30, 40],
	paginationOptions = {},
	onSuccess,
	onError,
	onFilter
}: UseTableConfig) {
	const loading = ref(true)
	const error = ref<Record<string, any> | null>(null)
	const list = ref([]) as Ref<T[]>
	const data = ref({}) as Ref<R>
	const initParams = cloneDeep(params)
	const pagination = {
		currentPage,
		pageSize,
		total: 0,
		layout: 'total, prev, pager, next, sizes',
		background: true,
		pageSizes: pageSizeOptions,
		onCurrentChange(currentPage) {
			pagination.currentPage = currentPage
			fetchList()
		},
		onSizeChange(size) {
			pagination.pageSize = size
			fetchList()
		},
		...paginationOptions
	}

	function fetchList() {
		onFilter && onFilter()
		loading.value = true
		get<R>({
			url,
			params: {
				...params,
				limit: pagination.pageSize,
				page: pagination.currentPage
			},
			config
		})
			.then(response => {
				data.value = response
				// @ts-ignore
				list.value = response
				pagination.total = 500
				// pagination.currentPage = data.page
				onSuccess && onSuccess()
			})
			.catch(err => {
				error.value = err
				onError && onError(err)
			})
			.finally(() => (loading.value = false))
	}

	function reset() {
		pagination.pageSize = pageSize
		pagination.currentPage = currentPage
		Object.assign(params, cloneDeep(initParams))
		fetchList()
	}

	function query() {
		pagination.currentPage = currentPage
		fetchList()
	}

	immediate && fetchList()

	return {
		error,
		list,
		data,
		loading,
		pagination,
		fetchList,
		reset,
		query
	}
}
